﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

namespace BBECServiceBusAdapter.Activities
{

    public sealed class AddResponseDetail : NativeActivity
    {
        #region Activity Arguments

        public InArgument<int> ErrorCode { get; set; }
        public InArgument<bool> CreateLogEntry { get; set; }
        public InArgument<string> AdditionalDetails { get; set; }

        #endregion

        protected override void Execute(NativeActivityContext context)
        {
            // if the ErrorDetails property has not been established, do it now
            if (context.Properties.Find("ErrorDetails") == null) { context.Properties.Add("ErrorDetails", new List<Helper.ErrorDetailInfo>()); }

            int _errorCode = ErrorCode.Get<int>(context);
            string _errorDescription = Helper.GetErrorCodeDescription(ErrorCode.Get<int>(context));
            if (!string.IsNullOrEmpty(AdditionalDetails.Get<string>(context)))
            {
                _errorDescription += Environment.NewLine + AdditionalDetails.Get<string>(context);
            }
            Helper.ErrorLevel _errorLevel;
            try
            {
                _errorLevel = (Helper.ErrorLevel)Enum.Parse(typeof(Helper.ErrorLevel), Helper.GetErrorCodeLevel(_errorCode));
            }
            catch
            {
                _errorLevel = Helper.ErrorLevel.Unknown;
            }

            // add the error information as a new ErrorDetailInfo member of the ErrorDetails property list
            ((List<Helper.ErrorDetailInfo>)context.Properties.Find("ErrorDetails")).Add(new Helper.ErrorDetailInfo() { 
                errorCode = _errorCode,
                errorDescription = _errorDescription,
                errorLevel = _errorLevel
            });

            if (CreateLogEntry.Get<bool>(context) == true)
            {
                Helper.CreateServiceBusAdapterLogEntry(
                    _errorLevel,
                    context.WorkflowInstanceId,
                    "(" + _errorCode.ToString() + ") " + _errorDescription);
            }
        }
    }
}
